<?php
class dpa_achievement {
	var $user_id;       // user id
	var $name;          // achievement identifier
	var $is_unlocked;   // if this achievement has been unlocked
	var $points;				// points rewarded
	var $counter;       // counter (used to count things)
	
	function dpa_achievement( $args ) {
		$this->_populate( $args );
	}


	/**
	 * Protected functions
	 */
	function _populate( $args ) {
		extract( $args, EXTR_SKIP );

		$this->user_id      = $user_id;
		$this->name         = $name;
		$this->is_unlocked  = $this->_get_unlocked();
		$this->points       = $this->_get_points();

		if ( $counter )
			$this->counter      = $this->_get_counter();
	}
	
	function _get_counter() {
		$result = get_usermeta( $this->user_id, 'dpa_' . $this->name . '_counter' );
		if ( empty( $result ) )
			$result = 0;
		
		return $result;
	}
	
	function _get_unlocked() {
		global $bp, $wpdb;

		$result = $wpdb->get_var( $wpdb->prepare( "SELECT achieved_at FROM {$bp->achievements->table_unlocked}, {$bp->achievements->table_achievements} WHERE user_id = %d AND {$bp->achievements->table_unlocked}.achievement_id = {$bp->achievements->table_achievements}.id AND {$bp->achievements->table_achievements}.short_name = %s LIMIT 1", $this->user_id, $this->name ) );
		return !empty( $result );
	}
	
	function _get_points() {
		global $bp, $wpdb;

		return $wpdb->get_var( $wpdb->prepare( "SELECT points FROM {$bp->achievements->table_achievements} WHERE short_name = %s LIMIT 1", $this->name ) );
	}


	/**
	 * Public functions
	 */
	function unlock_achievement( $send_notification=true ) {
		global $bp, $wpdb;

		if ( $this->is_unlocked() )
			return;

		do_action( 'dpa_unlock_achievement', $this->user_id, $this->name );	

		$achievement_id = $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$bp->achievements->table_achievements} WHERE short_name = %s LIMIT 1", $this->name ) );

		$wpdb->insert( $bp->achievements->table_unlocked, array( 'achievement_id' => $achievement_id, 'user_id' => $this->user_id, 'achieved_at' => current_time( 'mysql' ) ) );

		if ( $send_notification ) {
			bp_core_add_notification( $achievement_id, $this->user_id, $bp->achievements->id, 'new_achievement', $this->user_id );
			dpa_record_activity( $this->user_id, dpa_format_activity( $this->user_id, $achievement_id ), $achievement_id );

			do_action( 'dpa_unlock_achievement_notification', $this->user_id, $this->name );
    }

		dpa_update_userpoints( $this->user_id, $this->points );
	}

	function is_unlocked() {
		return ( $this->is_unlocked );
	}

	function increment_counter( $i = 1 ) {
		if ( defined( 'DPA_CHECKING' ) )
			return $this->counter;

		$this->counter += $i;
		return update_usermeta( $this->user_id, 'dpa_' . $this->name . '_counter',  $this->counter ); 
	}
}
?>